<?php

namespace app\site\controller;

use app\common\model\ShopJicaiClassModel;
use app\common\model\ShopJicaiGoodsModel;
use think\Request;

class ShopJicaiGoodsController extends BaseController
{
    private $jicaiClassModel;
    private $jicaiGoodsModel;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->jicaiClassModel = new ShopJicaiClassModel();
        $this->jicaiGoodsModel = new ShopJicaiGoodsModel();
    }

    /**
     * 集采列表
     */
    public function index()
    {
        $query          = $this->request->request();
        $jicaiStatus = $this->request->param('jicai_status',-1);
        if($jicaiStatus>-1){
            $map['jicai_status'] = $jicaiStatus;
        }
        $map['site_id'] = $this->getSiteId();
        $list           = $this->jicaiGoodsModel->where($map)->paginate(12, false, ['query' => $query]);
        $this->assign('query', $query);
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 申请集采
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $data   = $this->request->param();
            $result = $this->validate($data, [
                'class_id|集采分类'    => 'require',
                'sku_id|活动商品'      => 'require',
                'begin_time|开始日期'  => 'date',
                'end_time|结束日期'    => 'date',
                'jicai_price|集采价格' => 'float|>:0',
                'jicai_stock|集采数量' => 'number|>=:100',
            ]);
            if (true !== $result) {
                $this->error($result);
            }
            if($data['jicai_stock']>$data['goods_stock']){
                $this->error('集采数量大于商品库存量！');
            }
            if($data['jicai_price']>$data['simple_price']){
                $this->error('集采价格需小于商品销售价！');
            }
            $data['begin_time'] = strtotime($data['begin_time'].' 0:00:00');
            $data['end_time'] = strtotime($data['end_time'].' 23:59:59');
            if($data['begin_time']>$data['end_time']){
                $this->error('开始日期必须小于结束日期！');
            }
            $class = explode('#',$data['class_id']);
            $data['class_id'] = $class[0];
            $data['class_name'] = $class[1];
            $this->jicaiGoodsModel->addData($data);
            $this->success('操作成功！',url('index'));
        }
        $classList = $this->jicaiClassModel->order('class_sort')->select();
        $this->assign('classList', $classList);
        return $this->fetch();
    }

    /**
     * 删除集采
     */
    public function del(){
        $jicaiId = $this->request->param('jicai_id/d');
        $this->jicaiGoodsModel->where('jicai_id',$jicaiId)->where('jicai_status',0)->delete();
        $this->success('操作成功！');
    }

}